package com.cn.lp.export.client;

import com.cn.lp.export.client.base.ExportConfig;
import com.cn.lp.export.client.base.context.CommandResult;
import com.cn.lp.export.client.base.context.ExportException;
import com.cn.lp.export.client.base.context.ResponseResult;
import com.cn.lp.export.client.export.*;
import com.cn.lp.export.client.utils.HttpClientAide;
import com.cn.lp.export.client.utils.JSONAide;
import com.cn.lp.export.client.utils.ObjectAide;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Description: 请描述你的文件
 *
 * @author wuqirong
 * @date 2020-10-19
 * <p>
 * All rights Reserved, Designed www.xiao100.com
 */
@Service
public class ExportClient {

    @Autowired
    private ExportConfig exportConfig;

    private static Logger logger = LoggerFactory.getLogger(ExportClient.class);

    /**
     * 创建导出任务
     *
     * @param mappingList
     * @param excelName
     */
    public CreateExportTaskResponse createExportTask(String excelName, List<Export2EntityMapping> mappingList, long totalNum) {
        CreateExportTaskRequest createTask = new CreateExportTaskRequest();
        createTask.setExportFieldMap(assemblyExportField(mappingList));
        createTask.setExcelName(excelName);
        createTask.setTotalNum(totalNum);
        String message = HttpClientAide.postJsonParams(exportConfig.getExportServerUrl() + "/export/task/create", JSONAide.toJson(createTask));
        ResponseResult<CreateExportTaskResponse> result = JSONAide.toObject(message, new TypeReference<ResponseResult<CreateExportTaskResponse>>() {
        });
        if (!result.isSuccess()) {
            logger.error(excelName + "导出Excel异常：" + result.getErrorMsg());
            throw new ExportException(excelName + "导出Excel出错，请联系管理员");
        }
        return result.getMessage();
    }

    /**
     * 上传导出数据
     *
     * @param taskId
     * @param exportData
     * @param dataNum
     */
    public boolean uploadExportData(long taskId, ExportData exportData, long dataNum) {
        UploadExportDataRequest uploadRequest = new UploadExportDataRequest();
        uploadRequest.setTaskId(String.valueOf(taskId));
        uploadRequest.setSort(exportData.getSort());
        uploadRequest.setData(ObjectAide.objectToBlob(exportData));
        uploadRequest.setDataNum(dataNum);
        String message = HttpClientAide.postJsonParams(exportConfig.getExportServerUrl() + "/export/data/upload", JSONAide.toJson(uploadRequest));
        ResponseResult<Boolean> result = JSONAide.toObject(message, new TypeReference<ResponseResult<Boolean>>() {
        });
        if (!result.isSuccess()) {
            logger.error(taskId + "导出任务上传数据失败：" + result.getErrorMsg());
            return false;
        }
        return true;
    }

    /**
     * 获取任务状态
     *
     * @param taskId
     * @return
     */
    public ExportStatus getTaskStatus(long taskId) {
        String message = HttpClientAide.get(exportConfig.getExportServerUrl() + "/export/task/" + taskId + "/status", Collections.emptyMap());
        CommandResult<Integer> result = JSONAide.toObject(message, new TypeReference<ResponseResult<Integer>>() {
        });
        if (!result.isSuccess()) {
            logger.error(taskId + "获取任务状态失败：" + result.getErrorMsg());
            throw new ExportException(taskId + "获取任务状态失败，请联系管理员");
        }
        return ExportStatus.getById(result.getMessage());
    }

    /**
     * 取消任务
     *
     * @param taskId
     */
    public void cancelTask(long taskId) {
        String message = HttpClientAide.post(exportConfig.getExportServerUrl() + "/export/task/" + taskId + "/cancel", Collections.emptyMap());
        CommandResult<Boolean> result = JSONAide.toObject(message, new TypeReference<ResponseResult<Boolean>>() {
        });
        if (!result.isSuccess()) {
            logger.error("取消" + taskId + "任务失败：" + result.getErrorMsg());
            throw new ExportException("取消" + taskId + "任务失败，请联系管理员");
        }
    }

    /**
     * 装配导出字段
     */
    private LinkedHashMap<String, Object> assemblyExportField(List<Export2EntityMapping> mappingList) {
        LinkedHashMap<String, Object> exportFieldMap = new LinkedHashMap<>();
        for (Export2EntityMapping mapping : mappingList) {
            if (mapping.getEntityFieldName() != null) {
                exportFieldMap.put(mapping.getExportName(), mapping.getEntityFieldName());
            } else {
                if (!mapping.getSubMapping().isEmpty()) {
                    exportFieldMap.put(mapping.getExportName(), assemblyExportField(mapping.getSubMapping()));
                } else {
                    throw new ExportException(mapping.getExportName() + "对应字段不能为空");
                }
            }
        }
        return exportFieldMap;
    }

}
